<template>
  <el-container>
    <!--    <el-header height="30px">-->
    <!--    </el-header>-->
    <el-container>
      <el-aside width="300px">
        <el-container>
          <el-aside width="70px" style="background-color: #7494f1;text-align: center;">
            <div style="padding-top: 10px">
              <el-button class="myAvatar">{{ loginUser.userName }}</el-button>
            </div>
            <div style="padding-top: 10px">
              <el-button :style="{'background-color':showUsers?'#C5C5C5FF':'white'}" class="el-icon-user" @click="showUserOrSessionList(true)"></el-button>
            </div>
            <div style="padding-top: 10px">
              <el-badge :is-dot="unreadSessions.size>0" class="item">
                <el-button :style="{'background-color':!showUsers?'#C5C5C5FF':'white'}" class="el-icon-chat-line-round" @click="showUserOrSessionList(false)"></el-button>
              </el-badge>
            </div>
            <div style="padding-top: 10px;">
              <el-button class="el-icon-switch-button" @click="quit"></el-button>npm
            </div>
          </el-aside>
          <el-main style="background-color: #D3DCE6;">
            <div v-if="showUsers && loginUsers != null && loginUsers.length>0">
              <div v-for="item in loginUsers">
                <el-button style="width: 190px;" @click="toUser($event)">{{ item.userName }}</el-button>
              </div>
            </div>
            <div v-if="!showUsers && chatSessions != null && chatSessions.length>0">
              <div v-for="item in chatSessions">
                <el-badge :is-dot="unreadSessions.has(item.msgTo)" class="item">
                  <el-button @click="toUser($event)" :style="{width: '190px','background-color':to == item.msgTo?'#C5C5C5FF':'white'}">{{ item.msgTo }}</el-button>
                </el-badge>
              </div>
            </div>
          </el-main>
        </el-container>
      </el-aside>
      <el-container v-if="!showUsers && to != null && to !=''">
        <el-main>
          <div v-if="msgList != null && msgList.length>0">
            <div v-for="item in msgList">
              <div v-if="item.msgFrom != null" :style="{'text-align': item.msgFrom==loginUser.userName?'right':'left'}">
                <div v-if="item.msgFrom==loginUser.userName" style="margin: 5px">
                  <span>{{ item.msgContent }}</span>
                  <el-tag class="chatAvatar">{{ item.msgFrom }}</el-tag>
                </div>
                <div v-if="item.msgFrom!=loginUser.userName" style="margin: 5px">
                  <el-tag class="chatAvatar">{{ item.msgFrom }}</el-tag>
                  <span>{{ item.msgContent }}</span>
                </div>
              </div>
            </div>
          </div>
        </el-main>
        <el-footer>
          <el-row style="margin: 10px;">
            <el-col :span="20">
              <el-input v-model="msg" clearable @keyup.enter.native="sent"></el-input>
            </el-col>
            <el-col :span="4">
              <el-button @click="sent()">发送</el-button>
            </el-col>
          </el-row>
        </el-footer>
      </el-container>
    </el-container>
  </el-container>
</template>

<script>
export default {
  name: "Layout",
  data: function () {
    return {
      loginUser: {
        userName: 'zs',
        password: '123',
      },

      msg: null,
      to: null,
      isDot: true,
      ws: null,
      showUsers: true,
      loginUsers: [],
      chatSessions: [],
      msgList: [],
      unreadSessions: new Set(),
      pingIntervalSeconds:30000,//心跳连接时间
      heartTimer: null,//心跳定时器
    }
  },
  mounted() {
    this.loginUser.userName = this.getSession(this.projectName + "UserName");
    this.createconnect();
    this.getUsers();
  },
  destroyed(){
    if (this.ws != null) {
      console.log("关闭连接...")
      this.ws.close();
    }
    this.heartTimer && clearInterval(this.heartTimer);
  },
  methods: {
    quit(){
      this.removeSession(this.projectName + "UserName");
      this.removeSession(this.projectName + "Token");
      this.$router.replace('/Login')
    },
    showUserOrSessionList(flag) {
      this.showUsers = flag;
      if (flag) {
        this.getUsers();
      } else {
        this.getChatSessions();
      }
    },
    toUser(e) {
      this.msgList = [];
      this.to = e.target.innerText;
      if(this.showUsers){
        this.addChatSession();
        this.getChatSessions();
        this.showUsers = false;
      }
      this.unreadSessions.delete(this.to)
      this.getChatMsg();
    },
    addChatSession() {
      if (this.showUsers) {
        let url = `/chatSession/chatSessionPlus`;
        let chatSession = {}
        chatSession.msgFrom = this.loginUser.userName;
        chatSession.msgTo = this.to;
        this.ajax(url, chatSession, "POST")
      }
    },
    getChatMsg() {
      let url = `/chatMsg/getChatMsgs`;
      let chatMsg = {}
      chatMsg.msgFrom = this.loginUser.userName;
      chatMsg.msgTo = this.to;
      this.ajax(url, chatMsg, "POST").then(res => {
        if (res.success) {
          this.msgList = res.data;
        }
      })
    },
    sent() {
      let msg = {
        msgType: 1
      }
      msg.msgFrom = this.loginUser.userName;
      msg.msgTo = this.to;
      msg.msgContent = this.msg
      this.msgList.push(msg);
      this.ws.send(JSON.stringify(msg));
      this.msg = '';

    },
    getChatSessions() {
      let url = `/chatSession/getChatSessions`;
      let chatSession = {
        "msgFrom": this.loginUser.userName
      };
      this.ajax(url, chatSession, "POST").then(res => {
        if (res.success) {
          this.chatSessions = res.data;
        }
      })
    },
    getUsers() {
      let url = `/loginUser/getUsers`;
      let loginUser = this.loginUser;
      loginUser.password = null;
      this.ajax(url, loginUser, "POST").then(res => {
        if (res.success) {
          this.loginUsers = res.data;
        }
      })
    },
    createconnect() {
      // const websocket = new WebSocket('ws://150.158.33.191:1024/channel');
      const websocket = new WebSocket('ws://localhost:1024/channel');
      websocket.onopen = () => {
        this.ws = websocket;
        // 上传用户信息 握手??
        let userInfo = {
          msgFrom: this.loginUser.userName,
          msgType: 0
        }
        this.ws.send(JSON.stringify(userInfo))
        console.log(`链接建立...`);
        //开启心跳
        this.start();
      }
      websocket.onmessage = e => {
        let res = JSON.parse(e.data);
        console.log(res)
        if (res.msgType == 1) {
          this.unreadSessions.add(res.msgFrom);
          this.msgList.push(res)
        }
        if (res.msgType == 11) {
          console.log("接受到了pong消息...")
        }
      }
      websocket.onclose = e => {
        let {code, reason} = e;
        this.heartTimer && clearInterval(this.heartTimer);
        console.log(`链接断开:code=${code}, reason=${reason}`);
      }
      websocket.onerror = e => {
        this.ws.close();
        console.log('链接异常:', e);
      }
    },
    //开启心跳
    start(){
      this.heartTimer = setInterval(()=>{
        console.log("开始发送心跳消息ping...")
        let heartMsg = {msgType:10};
        this.ws.send(JSON.stringify(heartMsg));
      }, this.pingIntervalSeconds)
    },
  },

  components: {}

}
</script>

<style scoped>
.sidebar-container {
  background-color: #2d3a4b;
  height: 100%;
}

.el-header, .el-footer {
  background-color: #B3C0D1;
  color: #333;
  text-align: center;
}

.el-aside {
  background-color: #D3DCE6;
  color: #333;
  text-align: center;
}

.el-main {
  background-color: #E9EEF3;
  color: #333;
  text-align: center;
}

.chatAvatar {
  /*background-color: #2d3a4b;*/
  min-width: 70px;
  text-align: center;
  margin: 1px 10px;
  border: 1px solid !important;
}

.myAvatar {
  /*background-color: #2d3a4b;*/
  /*border: 1px solid !important;*/
}
</style>
